package com.atguigu.ssyx.acl.utils;

import com.atguigu.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单权限处理工具类
 */
public class PermissionHelper {
    public static List<Permission> buildPermission(List<Permission> permissionList) {
        // 封装数据集合
        List<Permission> trees = new ArrayList<>();
        // 遍历所有菜单权限集合，得到所有一级菜单权限，pid=0
        for (Permission permission : permissionList) {
            // 判断当前权限菜单的pid=0, 即一级菜单
            if (permission.getPid() == 0) {
                permission.setLevel(1);
                // 从一级菜单开始遍历所有菜单权限，递归查找
                trees.add(findChildren(permission, permissionList));
            }
        }
        return trees;
    }

    /**
     * 递归查找子菜单, 根据id和pid是否相等
     * @param permission: 当前菜单权限节点
     * @param permissionList: 所有菜单权限集合
     * @return
     */
    private static Permission findChildren(Permission permission, List<Permission> permissionList) {
        permission.setChildren(new ArrayList<Permission>());
        // 遍历所有菜单权限集合
        for (Permission p : permissionList) {
            // 判断当前节点id=pid，封装并递归查找
            if (permission.getId().equals(p.getPid())) {
                int level = permission.getLevel() + 1;
                p.setLevel(level);
                if (permission.getChildren().isEmpty()) {
                    permission.setChildren(new ArrayList<Permission>());
                }
                // 封装下一级菜单权限数据
                permission.getChildren().add(findChildren(p, permissionList));
            }
        }
        return permission;
    }
}
